//
//  SetAccountViewController.m
//  PalmChangtu
//
//  Created by shaorui on 15/6/18.
//  Copyright (c) 2015年 PalmChangtu. All rights reserved.
//

#import "SetAccountViewController.h"
#import "MainTabbarController.h"
#import "ContactUSViewController.h"
#import "MeLeaveMessageViewController.h"
#import "FeedBackViewController.h"
#import "ShareUserModel.h"
#import "SVProgressHUD.h"
#import "AFNetworking.h"
#import "Common.h"
#import "LoadingView.h"
#import "BaseUrlConfig.h"
#import "NetWarningView.h"
#import "MTLJSONAdapter.h"
#import "AppDelegate.h"
#import "APService.h"
@interface SetAccountViewController ()
{

    NSInteger intISPush;
    NSMutableDictionary            *statusDic;

}
@end

@implementation SetAccountViewController
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        
    }
    return self;
}


#pragma mark - App检测推送
-(void)viewDidAppear:(BOOL)animated
{
    
    [self RequestWith];
    
    NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"status.plist"];
    if ([[NSFileManager defaultManager]fileExistsAtPath:path isDirectory:NO]) {
        
        statusDic = [[NSDictionary dictionaryWithContentsOfFile:path]mutableCopy];
    }else {
        statusDic=[[NSMutableDictionary alloc]initWithObjectsAndKeys:@1,@"status" ,nil];
    }
    
    
    if ([[statusDic objectForKey:@"status"]integerValue]==1) {
        //如果关就设为开
        //可以添加自定义categories
        [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                       UIUserNotificationTypeSound |
                                                       UIUserNotificationTypeAlert)
                                           categories:nil];
        self.switchPush.on = YES ;
        intISPush = 1;
        
    }
    else
    {
        //如果开就设为关
        [[UIApplication sharedApplication] unregisterForRemoteNotifications];
        self.switchPush.on = NO ;
        intISPush = 0;
    }

    
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [_btnClearCache removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    [_btnClearCache addTarget:self action:@selector(clearCacheSuccess:) forControlEvents:UIControlEventTouchUpInside];
    
    

    // Do any additional setup after loading the view from its nib.
//    self.view.backgroundColor  = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bgimage"]];

    [_v_Top.lalTitel setText:@"设置"];
    
    [_v_Top.btnGoback setHidden:NO];
    _v_Top.parentController = self.navigationController;
    intISPush = 1;

    
    [self.switchPush removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [self.switchPush addTarget:self action:@selector(customSwitchSetStatus:) forControlEvents:UIControlEventTouchUpInside];


    [self.btnFeedBack removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [self.btnFeedBack addTarget:self action:@selector(btnFeedBack:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.btnAboutWe removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [self.btnAboutWe addTarget:self action:@selector(btnAboutWe:) forControlEvents:UIControlEventTouchUpInside];

    [self.btnLeaveMessage removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [self.btnLeaveMessage addTarget:self action:@selector(btnLeaveMessageAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.btnLoginOut removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [self.btnLoginOut addTarget:self action:@selector(btnLoginOutAction:) forControlEvents:UIControlEventTouchUpInside];

    
//    [self.btnLoginOutAction removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
//    
//    [self.btnLoginOutAction addTarget:self action:@selector(btnLoginOut:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    

}


-(void)clearCacheSuccess:(UIButton *)btnClearCache

{
    dispatch_async(
                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                   , ^{
                       NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
                       
                       NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                           //                       NSLog(@"files :%d",[files count]);
                       for (NSString *p in files) {
                           NSError *error;
                           NSString *path = [cachPath stringByAppendingPathComponent:p];
                           if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                               [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                           }
                       }
                       
                       
                       [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});
}


-(void)clearCacheSuccess
{
    
    
    
    
    [SVProgressHUD showWithStatus:@"清理成功"];
    
    
    NSLog(@"清理成功");
    
    
    [NSThread sleepForTimeInterval:1.50];
    
    [SVProgressHUD dismiss];
    
    
}
#pragma mark - customSwitch delegate
-(void)customSwitchSetStatus:(UISwitch *)status
{
    NSString *path = [NSString stringWithFormat:@"%@/Documents/status.plist",NSHomeDirectory()];
    
    
    if (status.on)
    {
        [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                       UIUserNotificationTypeSound |
                                                       UIUserNotificationTypeAlert)
                                           categories:nil];
        [statusDic setValue:@1 forKey:@"status"];
        [statusDic writeToFile:path atomically:YES];
        intISPush = 1;
        
        
        
    }
    else
    {
        
        
        intISPush = 0;
        [[UIApplication sharedApplication] unregisterForRemoteNotifications];
        //0是关因为图片为开就设为开，否侧相反
        [statusDic setValue:@0 forKey:@"status"];
        [statusDic writeToFile:path atomically:YES];
        
    }
    
    
    [self RequestWith];
    
    
    
}

-(void)btnFeedBack:(UIButton *) bution
{

    
    
    
    FeedBackViewController * feedback = [[FeedBackViewController alloc] initWithNibName:@"FeedBackViewController" bundle:nil];
    [self.navigationController pushViewController:feedback animated:YES];
    
    


}


-(void)btnAboutWe:(UIButton *) AboutWe
{
    
    ContactUSViewController * ContactUSView  = [[ContactUSViewController alloc] initWithNibName:@"ContactUSViewController" bundle:nil];
    [self.navigationController pushViewController:ContactUSView animated:YES];

    
    
    
    
}
-(void)btnLeaveMessageAction:(UIButton *) LeaveMessage
{
    
    MeLeaveMessageViewController * MeLeaveMessage = [[MeLeaveMessageViewController alloc] initWithNibName:@"MeLeaveMessageViewController" bundle:nil];
    [self.navigationController pushViewController:MeLeaveMessage animated:YES];
    
    
    
    
    
    
}
-(void)btnLoginOutAction:(UIButton *)LoginOut
{
    
    
    
    
    ShareUserModel  *user = [ShareUserModel shareUserModel];
    if (user.isLogined) {
        user.isLogined = NO;
        
        [user LogOutUser];
        
    }
    
    
    [self.navigationController popToRootViewControllerAnimated:YES];
    MainTabbarController * MainVc =[MainTabbarController  ShareTabBarController];
    [MainVc checkIsUserLogin];
    
}







#pragma mark - network     个人信息

-(void)RequestWith
{

    
    [[LoadingView shareLoadingView] show];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应

    NSString *strUrl = [NSString stringWithFormat:@"%@%@", HostServer,updateBuyerPushAction];
    
    /*说明	英文名	类型
     用户id	userId	varchar
     是否推送	isPush	varchar
     登录名	loginName	varchar
     会话id	sessionId	varchar*/
    
    NSDictionary *params = @{
                             @"userId":[NSString stringWithFormat:@"%@",[ShareUserModel shareUserModel].user.user_id],
                             @"sessionId":[NSString stringWithFormat:@"%@",[ShareUserModel shareUserModel].user.sessionId],
                             @"loginName":[NSString stringWithFormat:@"%@",[ShareUserModel shareUserModel].user.phone],
                             @"isPush":[NSString stringWithFormat:@"%@",[NSNumber numberWithInteger:intISPush]],
                             };
    
    [manager POST:strUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSDictionary *dicRespon = responseObject;
         [self RequestSuccessWith:dicRespon];
         
         [[LoadingView shareLoadingView] dismissAnimated:YES];
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [[LoadingView shareLoadingView] dismissAnimated:YES];
         [[NetWarningView sharedNetWarningView] show];  //警告网络异常
         NSLog(@"Error: %@", error);
     }];
}

-(void)RequestSuccessWith:(NSDictionary *)dicRespon
{
    
    
    
    NSString * code = [dicRespon objectForKey:@"success"];
    if (code.integerValue ==1)
        {
        
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];
        
        }
    else
        {
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];
        
        }}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
